const express = require('express');
const bodyParser = require('body-parser');
const QRCode = require('qrcode');
const fs = require("fs");
const cors = require("cors");
const {join} = require("path");
// const WechatPay = require("wechat-pay-nodejs");
const app = express();
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/static', express.static('static'));
// 初始化微信支付
// const wechatPayInstance = new WechatPay.WechatPay({
//     appid: 'your_app_id',
//     mchid: '1705396355',
//     cert_private_content: Buffer.from('your_apiclient_key.pem'),
//     cert_public_content: Buffer.from('your_apiclient_cert.pem')
// });

// 创建订单并生成二维码
app.get('/query-product/:productId', async (req, res) => {
    const productId = req.params.productId;
    res.json({
        status: "success",
        data: productsMap[productId]
    });
});
app.get('/create-order/:orderId', async (req, res) => {
    let out_trade_no = req.params.orderId;
    let [productId, timestamp, randomNum] = out_trade_no.split("-");
    productId = productId.trim()
    // 从获取订单金额
    if (productId in productsMap){
        const secretUrl = productsMap[productId].Secrets;
        try {
            const result = {
                code_url: secretUrl
            }
            const codeUrl = result.code_url;
            const buffer = await QRCode.toBuffer(codeUrl, {
                type: 'png', // 指定图片格式为PNG
                color: {
                    dark: '#000000', // 指定二维码颜色
                    light: '#ffffff' // 指定背景颜色
                },
                width: 200, // 指定二维码宽度
                height: 200 // 指定二维码高度
            });
            // 将二维码图片转换为Base64格式
            const base64Image = buffer.toString('base64');
            const qrCodeUrl = `data:image/png;base64,${base64Image}`;
            // 动态生成HTML内容
            const html = `
                <div class="payment">
                    <h1>请用支付宝扫码支付</h1>
                    <div id="product-info">${productsMap[productId].ProductName}</div>
                    <div id="order-no">${out_trade_no}</div>
                    <img id="qrcode" src="${qrCodeUrl}" alt="QR Code"/>
                    <div id="password-container"></div>
                </div>
            `;

            // 设置响应头，指定返回的是图片
            res.type('html');
            // 将二维码图片作为响应返回
            res.send(html);
        } catch (err) {
            console.error(err);
            res.status(500).json({ error: err.message });
        }
    } else {
        const html = `
                <div class="payment">
                    <h1>资源尚未准备好，暂无法支付购买！</h1>
                </div>
            `;
        // 设置响应头，指定返回的是图片
        res.type('html');
        // 将二维码图片作为响应返回
        res.send(html);
    }
});
app.get('/create-order-qrcode/:orderId', async (req, res) => {
    // const { body, out_trade_no, total_fee, spbill_create_ip, notify_url } = req.body;
    // 计算订单号
    // const productId = req.params.productId;
    // const timestamp = Date.now();
    // const randomNum = Math.floor(Math.random() * 1000) + 1;
    let out_trade_no = req.params.orderId;
    let [productId, timestamp, randomNum] = out_trade_no.split("-");
    productId = productId.trim()
    // 从获取订单金额
    if (productId in productsMap){
        const secretUrl = productsMap[productId].Secrets;
        try {
            const result = {
                code_url: secretUrl
            }
            const codeUrl = result.code_url;
            const buffer = await QRCode.toBuffer(codeUrl, {
                type: 'png', // 指定图片格式为PNG
                color: {
                    dark: '#000000', // 指定二维码颜色
                    light: '#ffffff' // 指定背景颜色
                },
                width: 200, // 指定二维码宽度
                height: 200 // 指定二维码高度
            });
            // 设置响应头，指定返回的是图片
            res.type('png');

            // 将二维码图片作为响应返回
            res.send(buffer);
            // 生成二维码并返回给前端
            // const qrCodeUrl = await QRCode.toDataURL(codeUrl);
            // res.json({ qrCodeUrl });
        } catch (err) {
            console.error(err);
            res.status(500).json({ error: err.message });
        }
    } else {
        // 直接回送一张暂未提供的图片
        res.sendFile(join(__dirname, 'static/NotSupported.png'));
    }


});
app.get('/check-order/:orderId', async (req, res) => {
    const orderId = req.params.orderId;
    res.json({
        status: "success",
        data: {
            orderId: orderId,
            price: "19.99",
            secrets: "ayuekekvkdie"
        }
    });
});
app.get('/')
// 初始化数据库
const products = JSON.parse(fs.readFileSync(`./assets/products.json`, 'utf-8')).ProductList;
const productsMap = {};
products.forEach(p => {
    productsMap[p.ProductId] = p;
});

// app.all('*',function (req, res, next) {
//     res.setHeader("Access-Control-Allow-Origin", "*");
//     res.setHeader("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
//     res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials");
//     // res.setHeader("Content-Type", "application/json;charset=utf-8");
//     next();
// });

app.listen(3999, () => {
    console.log('Server is running on port 3999');
});
